package icu.yougan.trade.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import icu.yougan.trade.entity.ChartsItem;
import icu.yougan.trade.entity.IdleItem;
import icu.yougan.trade.entity.Order;
import icu.yougan.trade.entity.User;
import icu.yougan.trade.mapper.IdleItemMapper;
import icu.yougan.trade.mapper.OrderMapper;
import icu.yougan.trade.mapper.UserMapper;
import icu.yougan.trade.service.IdleItemService;
import icu.yougan.trade.vo.PageVo;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author:油柑
 * @changeByLyh
 * @Date:2024/5/18 22:23
 * @Version:v1.0.0
 * @Description:TODO
 **/
@Service
public class IdleItemServiceImpl implements IdleItemService {
    @Resource
    private IdleItemMapper idleItemMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderMapper orderMapper;
    @Override
    public boolean addIdleItem(IdleItem idleItem) {
        return idleItemMapper.insert(idleItem) == 1;
    }

    @Override
    public IdleItem getIdleItemById(Long id) {
        return idleItemMapper.getIdleById(id);
    }

    @Override
    public IdleItem getIdleItem(Long id,Long userId) {
        IdleItem idleItem = idleItemMapper.selectByPrimaryKey(id);
        if (idleItem != null) {
            User user = userMapper.selectByPrimaryKey(idleItem.getUserId());
            idleItem.setUser(user);
            if(user.getId()!=userId)
            {
                Integer idleClick = idleItem.getIdleClick();
                idleItem.setIdleClick(++idleClick);
                idleItemMapper.updateByPrimaryKey(idleItem);
            }
        }
        return idleItem;
    }

    @Override
    public List<IdleItem> getAllIdelItem(Long userId) {
        return idleItemMapper.getAllIdleItem(userId);
    }
    @Override
    public PageVo<IdleItem> getIdleItemByHot(int page, int nums) {
        List<IdleItem> list = idleItemMapper.findIdleItemByHot((page - 1) * nums, nums);
        //System.out.println("获取到当前热门商品为:"+list);
        if (list.size() > 0) {
            List<Long> idList = new ArrayList<>();
            for (IdleItem i : list) {
                idList.add(i.getUserId());
            }
            List<User> userList = userMapper.findUserByList(idList);
            Map<Long, User> map = new HashMap<>();
            for (User user : userList) {
                map.put(user.getId(), user);
            }
            for (IdleItem i : list) {
                i.setUser(map.get(i.getUserId()));
            }
        }
        int count =list.size();
        return new PageVo<>(list, count);
    }
    @Override
    public PageVo<IdleItem> findIdleItem(String findValue, int page, int nums) {
        List<IdleItem> list = idleItemMapper.findIdleItem(findValue, (page - 1) * nums, nums);
        if (list.size() > 0) {
            List<Long> idList = new ArrayList<>();
            for (IdleItem i : list) {
                idList.add(i.getUserId());
            }
            List<User> userList = userMapper.findUserByList(idList);
            Map<Long, User> map = new HashMap<>();
            for (User user : userList) {
                map.put(user.getId(), user);
            }
            for (IdleItem i : list) {
                i.setUser(map.get(i.getUserId()));
            }
        }
        int count = idleItemMapper.countIdleItem(findValue);
        return new PageVo<>(list, count);
    }



    @Override
    public PageVo<IdleItem> findIdleItemByLabel(int idleLabel, int page, int nums) {
        int idleLabelDetails=idleLabel;

        List<IdleItem> list;
        if(idleLabelDetails<100)
        {
            list = idleItemMapper.findIdleItemByLabel(idleLabel, (page - 1) * nums, nums);
        }
        else
        {
            list =idleItemMapper.findIdleItemByLabelDetails(idleLabelDetails,(page-1)*nums,nums);
        }
        if (list.size() > 0) {
            List<Long> idList = new ArrayList<>();
            for (IdleItem i : list) {
                idList.add(i.getUserId());
            }
            List<User> userList = userMapper.findUserByList(idList);
            Map<Long, User> map = new HashMap<>();
            for (User user : userList) {
                map.put(user.getId(), user);
            }
            for (IdleItem i : list) {
                i.setUser(map.get(i.getUserId()));
            }
        }

        int count = idleItemMapper.countIdleItemByLable(idleLabel);
        return new PageVo<>(list, count);
    }
    //根据价格排序
    @Override
    public PageVo<IdleItem> findIdleItemByPrice(Double minPrice, Double maxPrice, int page, int nums) {
        List<IdleItem> list = idleItemMapper.findIdleItemByPrice(minPrice,maxPrice,(page - 1) * nums, nums);

        if (list.size() > 0) {
            List<Long> idList = new ArrayList<>();
            for (IdleItem i : list) {
                idList.add(i.getUserId());
            }
            List<User> userList = userMapper.findUserByList(idList);
            Map<Long, User> map = new HashMap<>();
            for (User user : userList) {
                map.put(user.getId(), user);
            }
            for (IdleItem i : list) {
                i.setUser(map.get(i.getUserId()));
            }
        }
        int count = idleItemMapper.countIdleItemByPrice(minPrice,maxPrice);
        return new PageVo<>(list, count);
    }

    @Override
    public PageVo<IdleItem> findIdleItemByMix(Double minPrice, Double maxPrice, Integer idleLabel,int page, int nums) {
        List<IdleItem> list=new ArrayList<>();
        int idleLabelDetails=idleLabel;
        if(idleLabelDetails<100)
         list = idleItemMapper.findIdleItemByMix(minPrice,maxPrice,idleLabel,(page - 1) * nums, nums);
        else
            list=idleItemMapper.findIdleItemByMixDetails(minPrice,maxPrice,idleLabelDetails,(page - 1) * nums, nums);
        if (list.size() > 0) {
            List<Long> idList = new ArrayList<>();
            for (IdleItem i : list) {
                idList.add(i.getUserId());
            }
            List<User> userList = userMapper.findUserByList(idList);
            Map<Long, User> map = new HashMap<>();
            for (User user : userList) {
                map.put(user.getId(), user);
            }
            for (IdleItem i : list) {
                i.setUser(map.get(i.getUserId()));
            }
        }
        int count = idleItemMapper.countIdleItemByMix(minPrice,maxPrice,idleLabel);

        return new PageVo<>(list, count);
    }

    @Override
    public void exportGoods(String startDate, String endDate, OutputStream outputStream) {
        // 查询数据
        List<IdleItem> goods = idleItemMapper.selectByDateRange(startDate, endDate);
        // 写入Excel
        try (ExcelWriter excelWriter = EasyExcel.write(outputStream).build()) {
            WriteSheet sheet = EasyExcel.writerSheet("商品数据")
                    .head(IdleItem.class)
                    .build();
            excelWriter.write(goods, sheet);
        }
    }

    @Override
    public boolean updateIdleItem(IdleItem idleItem) {
        return idleItemMapper.updateByPrimaryKeySelective(idleItem) == 1;
    }

    /**
     * 最高/最低价格排序
     * @param sort
     * @param page
     * @param nums
     * @return
     */
    @Override
    public PageVo<IdleItem> sortIdleItemByPrice(String sort, int page, int nums) {
        List<IdleItem> list = idleItemMapper.findIdleItemByPriceSort(sort,(page - 1) * nums, nums);

        if (list.size() > 0) {
            List<Long> idList = new ArrayList<>();
            for (IdleItem i : list) {
                idList.add(i.getUserId());
            }
            List<User> userList = userMapper.findUserByList(idList);
            Map<Long, User> map = new HashMap<>();
            for (User user : userList) {
                map.put(user.getId(), user);
            }
            for (IdleItem i : list) {
                i.setUser(map.get(i.getUserId()));
            }
        }
        int count = idleItemMapper.countAllIdleItem4Sort();

        return new PageVo<>(list, count);
    }

    @Override
    public PageVo<IdleItem> adminGetIdleList(int status, int page, int nums) {
        List<IdleItem> list = idleItemMapper.getIdleItemByStatus(status, (page - 1) * nums, nums);
        if (list.size() > 0) {
            List<Long> idList = new ArrayList<>();
            for (IdleItem i : list) {
                idList.add(i.getUserId());
            }
            List<User> userList = userMapper.findUserByList(idList);
            Map<Long, User> map = new HashMap<>();
            for (User user : userList) {
                map.put(user.getId(), user);
            }
            for (IdleItem i : list) {
                i.setUser(map.get(i.getUserId()));
            }
        }
        int count = idleItemMapper.countIdleItemByStatus(status);
        return new PageVo<>(list, count);
    }

    @Override
    public ChartsItem getChartsData(int page, int nums)
    {
        ChartsItem chartsItem=new ChartsItem();
        //获取未处理订单
        List<IdleItem> unProcessIdles=idleItemMapper.getIdleItemByStatus(4,(page - 1) * nums, nums);
        chartsItem.setPendingGoods((long) unProcessIdles.size());
        System.out.println("获取未处理订单信息:"+unProcessIdles);
        //获取当日售卖情况
        List<Order> todaySalesValues=orderMapper.getIdleToDaySales((page - 1) * nums, nums);
        double todayValues=0;
        double lastDayValues=0;
        for(Order todaySalesValue:todaySalesValues)
        {
            todayValues+=todaySalesValue.getOrderPrice().doubleValue();
        }
        //设置当日售卖数量
        chartsItem.setTodayOrders((long) todaySalesValues.size());
        System.out.println("今日售出数据为:"+todaySalesValues.size());
        //获取昨日售卖情况
        List<Order> lastDaySalesValues=orderMapper.getIdleToLastDaySales((page - 1) * nums, nums);
        for(Order lastDaySalesValue:lastDaySalesValues)
        {
            lastDayValues+=lastDaySalesValue.getOrderPrice().doubleValue();
        }

        //计算价格上升率
        double upRate = 0;
        upRate=((todayValues-lastDayValues)/((lastDayValues)==0?1:lastDayValues))*100;
        double formattedUpRate = Math.round(upRate * 100) / 100.0;
        chartsItem.setOrderTrend(Double.isFinite(formattedUpRate) ? formattedUpRate : 0);
        System.out.println("今日售出:"+todayValues+"昨日售出"+lastDayValues);

        //获取当日注册用户
        int newUsers=userMapper.getTodayRegister();

        chartsItem.setNewUsers((long) newUsers);

        //获取当前正在出售订单的分类(数量，所属大类)
        List<Integer>idlesCount=new ArrayList<>();
        List<String>idlesNames=new ArrayList<>();
        for(int i=1;i<=9;i++)
        {
            int idleLabel = getIdleLabel(i);
            if(idleLabel!=0)
            {
                idlesCount.add(idleLabel);
                idlesNames.add(getIdleLabelName(i));
            }
        }
        System.out.println("获取到当前的商品数量为:"+idlesCount+" 获取到当前的商品分类为："+idlesNames);
        chartsItem.setCategoryCount(idlesCount);
        chartsItem.setCategoryName(idlesNames);
        //获取近七天的日期
        List<String> days=getFormattedDates();
        chartsItem.setNearly7Days(days);
        //获取近七天的售卖情况
        List<BigDecimal> sales=orderMapper.getIdle7DaysSales();
        chartsItem.setNearly7DaysSales(sales);

        return chartsItem;
    }
    public List<String> getFormattedDates() {
        List<Date> dates = orderMapper.getIdle7DaysDate();
        return dates.stream()
                .map(date -> new SimpleDateFormat("yyyy-MM-dd").format(date))
                .collect(Collectors.toList());
    }
    private String getIdleLabelName(int Label)
    {
        Map<Integer,String> map=new HashMap<>();
        map.put(1,"数码");
        map.put(2,"服饰");
        map.put(3,"技能");
        map.put(4,"服务");
        map.put(5,"美妆");
        map.put(6,"玩具");
        map.put(7,"食品");
        map.put(8,"图书");
        map.put(9,"其他");
        return map.get(Label);
    }
    private int getIdleLabel(int idleLabel)
    {
        int i = idleItemMapper.countIdleItemByLable(idleLabel);
        System.out.println("获取商品的数量:"+i);
        return i;
    }
}
